import numpy as np
from scipy import ndimage
from skimage import data, util
from matplotlib import pyplot as plt 
# img为原图像
img = data.astronaut()
noise_img = np.zeros(img.shape)
new_img = np.zeros(img.shape)
for i in range(3):
    grayimg = data.astronaut()[:, :, i]
    # 对图像加入椒盐噪声
    noise_img[:, :, i] = util.random_noise(grayimg, mode='s&p',seed=None,clip=True)
    # 中值滤波
    n = 3
    new_img[:, :, i] = ndimage.median_filter(noise_img[:, :, i], (n, n))
# 显示图像
plt.rcParams['font.sans-serif'] = ['SimHei'] 
plt.rcParams['axes.unicode_minus'] = False
plt.subplot(1, 3, 1)
plt.axis('off')
plt.imshow(img)
plt.title('原图像')
plt.subplot(1, 3, 2)
plt.axis('off')
plt.imshow(noise_img)
plt.title('加噪图像')
plt.subplot(1, 3, 3)
plt.axis('off')
plt.imshow(new_img)
plt.title('中值滤波')
plt.savefig('彩色图像中值滤波结果.tif')